package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.AttendanceCycle;
import org.example.models.R;
import org.example.service.AttendanceCycleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: 鸢一折纸
 * @Email: 3498881048@qq.com
 * @Date: 2025/08/05 9:23
 * @Description:
 **/

@RestController
@RequestMapping("/attendanceCycle")
public class AttendanceCycleController {

    @Autowired
    private AttendanceCycleService attendanceCycleService;

    @GetMapping("/findAll")
    public R<List<AttendanceCycle>> getAllAttendanceCycle(){
        QueryWrapper<AttendanceCycle> query = new QueryWrapper<>();
                query.lambda().orderByDesc(AttendanceCycle::getAttendanceCycle);
        return R.success(attendanceCycleService.list(query));
    }

    @GetMapping("/page")
    public R<Page<AttendanceCycle>> getPageAttendanceCycle(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "4") int size,
            @RequestParam(name = "attendanceCycle", required = false) String attendanceCycle
    ){
        QueryWrapper<AttendanceCycle> query = new QueryWrapper<>();
        if (attendanceCycle != null && !attendanceCycle.isEmpty()) {
            query.lambda().like(AttendanceCycle::getAttendanceCycle, attendanceCycle);
        }

        query.lambda().orderByDesc(AttendanceCycle::getUpdatedAt);

        Page<AttendanceCycle> page = new Page<>(current, size);
        attendanceCycleService.page(page, query);
        return R.success(page);
    }

    @PostMapping("/insert")
    public R insertAttendanceCycle(@RequestBody AttendanceCycle attendanceCycle){
        QueryWrapper<AttendanceCycle> query = new QueryWrapper<>();
        query.lambda().eq(AttendanceCycle::getAttendanceCycle, attendanceCycle.getAttendanceCycle());

        if (attendanceCycleService.count(query) > 0) {
            return R.error("该考勤周期已存在");
        }

        return attendanceCycleService.save(attendanceCycle) ? R.success("添加成功") : R.error("添加失败");
    }

    @PostMapping("/update")
    public R updateAttendanceCycle(@RequestBody AttendanceCycle attendanceCycle){
        return attendanceCycleService.updateById(attendanceCycle) ? R.success("修改成功") : R.error("修改失败");
    }
}
